package com.lkm.app_ui;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.FileObserver;
import com.lkm.app_ui.log.SystemLogger;

import java.util.List;

import androidx.annotation.Nullable;


public class ANRReceiver extends BroadcastReceiver {

    private Context context;


    private final static String ANR_DIR_NAME = "/data/anr/";

    public static void init(Context context) {
        context = context.getApplicationContext();

        

//        intentFilter.addAction("android.intent.action.ANR");



        FileObserver fileObserver = new FileObserver(ANR_DIR_NAME, FileObserver.CLOSE_WRITE) {
            @Override
            public void onEvent(int event, @Nullable String path) {
                String filePath = ANR_DIR_NAME + path;
                if (filePath.contains("trace")) {
                    filterAnr(AppConst.getApplication());
                }
            }
        };
        try {
            fileObserver.startWatching();
        } catch (Exception e) {
        } finally {
            fileObserver.stopWatching();
        }

    }


    @Override
    public void onReceive(final Context context, Intent intent) {
        SystemLogger.log("收到ANR的广播"+intent.toString());
        filterAnr(context);
    }

    private static ActivityManager.ProcessErrorStateInfo filterAnr(Context context){
        ActivityManager.ProcessErrorStateInfo processErrorState = getProcessErrorState(context);
        if (processErrorState != null)
            if (processErrorState.pid == android.os.Process.myPid()) {
                SystemLogger.onANR();

                return processErrorState;
            }
        return null;
    }
    private static ActivityManager.ProcessErrorStateInfo getProcessErrorState(Context context) {

        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.ProcessErrorStateInfo> processErrorStates = activityManager.getProcessesInErrorState();
        for (ActivityManager.ProcessErrorStateInfo processErrorState : processErrorStates) {
            if (processErrorState.condition == ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING) {
                return processErrorState;
            }
        }
        return null;
    }


}
